package org.ratingviewer.ui.action;

import java.awt.event.ActionEvent;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.Document;

import org.ratingviewer.RatingViewer;

public class ActionSearch extends AbstractResourcedAction implements DocumentListener {

	private static final long serialVersionUID = 1L;

	private final RatingViewer ratingViewer;
	private final JTextField playerNameField;

	public ActionSearch(RatingViewer ratingViewer, JTextField playerNameField, JComponent shortcutHandler) {
		super("item.search", shortcutHandler);
		
		if (ratingViewer == null)
			throw new IllegalArgumentException("RatingViewer can't be null.");
		this.ratingViewer = ratingViewer;

		if (playerNameField == null)
			throw new IllegalArgumentException("PlayerNameField can't be null.");
		this.playerNameField = playerNameField;

		Document document = playerNameField.getDocument();
		document.addDocumentListener(this);

		setEnabled(computeState());
	}

	private boolean computeState() {
		String text = playerNameField.getText();
		return text != null && !text.trim().isEmpty();
	}

	public ActionSearch(RatingViewer ratingViewer, JTextField playerNameField) {
		this(ratingViewer, playerNameField, null);
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		nameChanged();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		nameChanged();
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		nameChanged();
	}

	private void nameChanged() {
		setEnabled(computeState());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String playerName = playerNameField.getText();
		ratingViewer.findPlayer(playerName);
	}

}
